package com.qqtop10.manager.controller.api;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alipay.util.AlipayNotify;
import com.qqtop10.manager.controller.OrderController;
import com.qqtop10.manager.model.Order;
import com.qqtop10.manager.service.AlipayBillService;
import com.qqtop10.manager.service.OrderDetailedService;
import com.qqtop10.manager.service.OrderService;

/**
 * 支付宝接口
 * 
 * @author Jovi
 *
 */
@RequestMapping("/pay/")
@Controller
public class AliPayController {

	private Logger logger = LoggerFactory.getLogger(AliPayController.class);

	@Autowired
	@Qualifier("orderService")
	private OrderService orderService;

	@Autowired
	@Qualifier("orderDetailedService")
	private OrderDetailedService orderDetailedService;

	@Autowired
	@Qualifier("alipayBillService")
	private AlipayBillService alipayBillService;
	
	/**
	 * 退款异步通知
	 * 
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("refundNotifyUrl.do")
	public void refund_notify_url(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		logger.info("退款异步通知。。。");
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 批次号
		String batch_no = new String(request.getParameter("batch_no").getBytes(
				"ISO-8859-1"), "UTF-8");

		// 批量退款数据中转账成功的笔数
		String success_num = new String(request.getParameter("success_num")
				.getBytes("ISO-8859-1"), "UTF-8");

		logger.info("success_num：" + success_num);
		// 批量退款数据中的详细信息
		String result_details = new String(request.getParameter(
				"result_details").getBytes("ISO-8859-1"), "UTF-8");

		logger.info("result_details：" + result_details);
		Order order = null;
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		try {
			if (AlipayNotify.verify(params)) {// 验证成功
				// 根据退款批次号获取订单uuid再获取订单对象
				order = orderService.selectByUuid(OrderController.p.get(
						batch_no).toString());
				if (order!=null && order.getStatus() == 5) {
					// 记录旧状态
					order.setOld_status(order.getStatus());
					// 设置退款成功状态
					order.setStatus(6);
					// 设置退款批次号
					order.setBatch_no(batch_no);
					// 退款时间
					order.setRefundtime(new Date());
					// 更新订单
					if (orderService.updateByUuidSelective(order) > 0) {
						// 移除
						OrderController.p.remove(batch_no);
						logger.info("退款处理成功：success");
						response.getOutputStream().print("success");
					} else {
						logger.info("退款处理成功：但订单已被处理");
					}
				}
				// 请不要修改或删除
			} else {// 验证失败
				logger.info("退款处理失败：fail");
				response.getOutputStream().print("fail");
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				logger.error("退款处理失败：fail");
				response.getOutputStream().print("fail");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		logger.info("退款异步通知。。。");
	}

	/**
	 * 退款同步通知
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */

	@RequestMapping("refund_return_url.do")
	public void refund_return_url(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		logger.info("退款同步通知.....");
		refund_notify_url(request, response);
		String result_details = request.getParameter("result_details");
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		if (result_details.indexOf("SUCCESS") > -1) {
			logger.info("退款成功：" + result_details);
			sb.append("alert('退款成功');");
		} else {
			logger.info("退款失败：" + result_details);
			sb.append("alert('退款失败：" + result_details + "');");
		}
		sb.append("</sceipt>");
		response.getOutputStream().print(sb.toString());
		logger.info("退款同步通知.....");
	}

	/**
	 * 转账异步通知
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "transferNotifyUrl.do", method = RequestMethod.POST)
	public void transferNotifyUrl(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		logger.info("转账异步通知开始。。。");
		try {
			// 获取支付宝POST过来反馈信息
			Map<String, String> params = new HashMap<String, String>();
			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter
					.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i]
							: valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
				// "gbk");
				logger.info("valueStr:" + valueStr);
				params.put(name, valueStr);
			}

			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

			// 通知校验ID
			String notify_id = new String(request.getParameter("notify_id")
					.getBytes("ISO-8859-1"), "UTF-8");
			// 批次号
			String batch_no = new String(request.getParameter("batch_no")
					.getBytes("ISO-8859-1"), "UTF-8");
			// 批量付款数据中转账成功的详细信息
			String success_details = request.getParameter(
					"success_details");
			if(success_details!=null){
				success_details =  new String(success_details.getBytes("ISO-8859-1"), "UTF-8");
			}

			logger.info("success_details:" + success_details);

			Order order = null;
			logger.info("开始验证。。。");
			if (AlipayNotify.verify(params)) {// 验证成功
				// 根据退款批次号获取订单uuid再获取订单对象
//				order = orderService.selectByUuid(OrderController.p.get(
//						batch_no).toString());
				order = orderService.selectByUuid(alipayBillService.getOrderUuidByBatch_no(batch_no));
				if(order!=null){
					// 支付给商家的异步通知id
					order.setPay_seller_notify_id(notify_id);
					// 支付给商家的批次号
					order.setPay_seller_batch_no(batch_no);
					// 更新支付给商家的信息
					orderService.paySeller(order);
					logger.info("转账成功，orderid:" + order.getOrderid());
					response.getOutputStream().print("success");
				}
				
			} else {// 验证失败
				logger.info("转账处理失败：fail");
				response.getOutputStream().print("fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("转账异步通知结束。。。");
	}
}
